package slef.xchen;

import java.util.List;

/**
 * @author xchen
 */
public class Turntable<T> {

	private final String tableName;
	private final String keyName;
	private Long current;
	private final int size;
	TimeArriveCallback<T> callback;
	private final String name;

	public Turntable(String name, int delaySeconds, TimeArriveCallback<T> callback) {
		tableName = "turntable:" + name + ":table";
		keyName = "turntable:" + name + ":currentIndex";
		current = Counter.incr(keyName);
		//时间优化参数
		this.size = delaySeconds + 2;
		this.callback = callback;
		this.name = name;
	}


	List<T> next() {
		current = Counter.incr(keyName);
		long index = current % size;
		String indexKey = "index_" + index;
		Slot<?> slot = DataHub.get(tableName, indexKey);
		if (null == slot) {
			return null;
		}
		List<T> dataList = (List<T>) slot.getDataList();
		if (null == dataList) {
			throw new RuntimeException("dataList should not empty");
		}
		slot.reset(tableName, indexKey);
		return dataList;
	}

	public Turntable<T> add(T data) {
		if (null == data) {
			return this;
		}
		long index = current % size;
		if (index == 0) {
			index = (long) size - 1;
		} else {
			index = index - 1;
		}
		String indexKey = "index_" + index;
		Slot<T> slot = (Slot<T>) DataHub.get(tableName, indexKey);
		if (null == slot) {
			slot = new Slot<>();
		}
		slot.add(data);
		DataHub.set(tableName, indexKey, slot);
		return this;
	}

	public TimeArriveCallback<T> getCallback() {
		return callback;
	}
	public String getName(){
		return name;
	}
}
